//
//  SpecificationView.m
//  phmall
//
//  Created by admin on 2017/12/11.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "SpecificationView.h"
#import "SpecificationCell.h"
#import "PPNumberButton.h"
#import "SpecificationModel.h"
#import "PropertyModel.h"

@interface SpecificationView ()<UITableViewDelegate,UITableViewDataSource,SpecificationCellDelegate>{
    CGFloat height;
    int flag;
    UIView *FooterView;
}

@property(nonatomic,strong)UIImageView *goodsImage;
@property(nonatomic,strong)UILabel *price;
@property(nonatomic,strong)UILabel *classify;
@property(nonatomic,strong)UILabel *repertory;
@property(nonatomic,strong)PPNumberButton *numberButton;
@property(nonatomic,strong)NSMutableArray *specification;
@property(nonatomic,strong)NSMutableArray *propertyArray;
@property(nonatomic,strong)NSMutableDictionary *selected;
@property(nonatomic,strong)NSMutableArray *classifyArray;
@end

@implementation SpecificationView
-(void)cancel:(UIButton *)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(cancel)]) {
        [self.delegate cancel];
    }
}
-(void)specAction:(UITableViewCell *)cell andSpec_id:(UIButton *)sender{
    NSIndexPath *indexPath=[self.myTabV indexPathForCell:cell];
    SpecificationModel *model=self.specification[indexPath.row];

    if (sender.selected) {
        [self.classifyArray removeObject:model.name];
        [self.selected setObject:[NSString stringWithFormat:@"%@:%@",model.name,sender.titleLabel.text] forKey:[NSString stringWithFormat:@"%ld",(long)indexPath.row]];
    }else{
        [self.selected setObject:@"" forKey:[NSString stringWithFormat:@"%ld",(long)indexPath.row]];
        [self.classifyArray addObject:model.name];
    }
    [self reloadView];
}
-(void)reloadView{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    for (int i=0; i<self.specification.count; i++) {
        NSString *key=[NSString stringWithFormat:@"%d",i];
        [array addObject:self.selected[key]];
    }
    NSInteger price=0;
    NSInteger inventory=0;
    
    BOOL haveProperty=NO;
    for (PropertyModel *model in self.propertyArray) {
        if ([array isEqualToArray:model.property]) {
            price=[model.price intValue];
            inventory=[model.inventory intValue];
            NSLog(@"%ld--%ld",(long)price,inventory);
            haveProperty=YES;
        }
    }
    
    if (haveProperty) {
        self.price.text=[NSString stringWithFormat:@"₱%ld",[self.model.goods_sale_price intValue]+price];
        self.repertory.text=[NSString stringWithFormat:@"%@:%ld%@",Localized(@"库存"),inventory,Localized(@"件")];
        self.numberButton.maxValue = inventory;
    }else{
        self.price.text=[NSString stringWithFormat:@"₱%@",self.model.goods_sale_price];
        self.repertory.text=[NSString stringWithFormat:@"%@:%@%@",Localized(@"库存"),self.model.goods_stock,Localized(@"件")];
        self.numberButton.maxValue = [self.model.goods_stock intValue];
    }
    
    if (self.classifyArray.count==0) {
        self.classify.text = [NSString stringWithFormat:@"%@:%@",Localized(@"已选择"),[array componentsJoinedByString:@" "]];
    }else{
        self.classify.text = [NSString stringWithFormat:@"%@:%@",Localized(@"请选择"),[self.classifyArray componentsJoinedByString:@" "]];
    }
}
-(instancetype)init{
    if (self=[super init]) {
        UIView *headerView = [UIView new];
        [self addSubview:headerView];
        [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
            make.left.equalTo(self);
            make.right.equalTo(self);
            make.height.mas_equalTo(120);
        }];
        headerView.backgroundColor=[UIColor whiteColor];
        
        UIButton *cancel=[UIButton buttonWithType:UIButtonTypeCustom];
        [cancel setImage:[UIImage imageNamed:@"取消"] forState:UIControlStateNormal];
        [cancel addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:cancel];
        [cancel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self).with.offset(10);
            make.right.equalTo(self).with.offset(-10);
            make.height.mas_equalTo(25);
            make.width.mas_equalTo(25);
        }];
        
        self.goodsImage=[[UIImageView alloc]init];
        [headerView addSubview:self.goodsImage];
//        self.goodsImage.image=[UIImage imageNamed:@"图片"];
        [self.goodsImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.offset(10);
            make.bottom.offset(-10);
            make.width.mas_equalTo(self.goodsImage.mas_height);
        }];
        
        self.classify=[UILabel new];
        self.classify.text=Localized(@"请选择规格");
        self.classify.numberOfLines=2;
        self.classify.textColor=[UIColor colorWithHexString:@"#adadad"];
        self.classify.textAlignment=NSTextAlignmentLeft;
        self.classify.font=[UIFont systemFontOfSize:13];
        [headerView addSubview:self.classify];
        [self.classify mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.goodsImage.mas_bottom);
            make.left.equalTo(self.goodsImage.mas_right).with.offset(20);
            make.right.equalTo(headerView.mas_right).with.offset(-20);
        }];
        
        self.repertory=[UILabel new];
//        self.repertory.text=@"库存:1548";
        self.repertory.textColor=[UIColor colorWithHexString:@"#adadad"];
        self.repertory.font=[UIFont systemFontOfSize:13];
        [headerView addSubview:self.repertory];
        [self.repertory mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.classify.mas_top).with.offset(-5);
            make.left.equalTo(self.classify);
            make.right.equalTo(headerView.mas_right).with.offset(-20);
        }];
        
        
        self.price=[UILabel new];
        self.price.text=@"₱154";
        self.price.textColor=[UIColor orangeColor];
        self.price.font=[UIFont systemFontOfSize:22];
        [headerView addSubview:self.price];
        [self.price mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.repertory.mas_top).with.offset(-5);
            make.left.equalTo(self.classify);
            make.right.equalTo(headerView.mas_right).with.offset(-20);
        }];


        UILabel *line=[UILabel new];
        line.backgroundColor=[UIColor groupTableViewBackgroundColor];
        [headerView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.goodsImage.mas_bottom).offset(10);
            make.left.equalTo(headerView).with.offset(20);
            make.right.equalTo(headerView).with.offset(-20);
            make.height.mas_equalTo(1);
        }];

        self.myTabV.backgroundColor=[UIColor whiteColor];
        [self addSubview:self.myTabV];
        [self.myTabV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(headerView.mas_bottom);
            make.left.equalTo(self);
            make.right.equalTo(self);
            make.bottom.equalTo(self.mas_bottom).with.offset(-49);
        }];
        
        self.confirm=[UIButton buttonWithType:UIButtonTypeCustom];
        [self addSubview:self.confirm];
        [self.confirm setTitle:Localized(@"确认") forState:UIControlStateNormal];
        [self.confirm addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
        [self.confirm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.confirm.backgroundColor=[UIColor orangeColor];
        //    [logOut setBackgroundImage:[UIImage imageNamed:@"背景渐变条"] forState:UIControlStateNormal];
        [self.confirm mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.offset(49);
            make.bottom.equalTo(self);
            make.left.equalTo(self);
            make.right.equalTo(self.mas_right);
        }];
        
        FooterView = [[UIView alloc]init];
        FooterView.backgroundColor=[UIColor whiteColor];
        
        UILabel *purchase=[UILabel new];
        purchase.text=Localized(@"购买数量");
        purchase.textAlignment=NSTextAlignmentCenter;
        purchase.textColor=[UIColor blackColor];
        purchase.font=[UIFont systemFontOfSize:13];
        [FooterView addSubview:purchase];
        [purchase mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(FooterView).with.offset(20);
            make.top.equalTo(FooterView).with.offset(0);
            make.height.offset(40);
        }];
        
        
        self.numberButton = [[PPNumberButton alloc]init];
        //设置边框颜色
        self.numberButton.borderColor = [UIColor colorWithHexString:@"#adadad"];
        // 开启抖动动画
        self.numberButton.shakeAnimation = YES;
        // 设置最小值
        self.numberButton.minValue = 1;
        // 设置最大值
        self.numberButton.maxValue = 100;
        // 设置输入框中的字体大小
        self.numberButton.inputFieldFont = 15;
        self.numberButton.increaseTitle = @"＋";
        self.numberButton.decreaseTitle = @"－";
        [FooterView addSubview:self.numberButton];
        [self.numberButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(20);
            make.top.equalTo(purchase.mas_bottom);
            //        make.right.equalTo(self.edit.mas_left).offset(-15);
            make.width.offset(160);
            make.height.offset(30);
            make.bottom.offset(-20);
        }];
        //全部控件添加完成后重新计算一遍高度
        CGFloat headerHeight = [FooterView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
        CGRect frame = FooterView.bounds;
        frame.size.height = headerHeight;
        FooterView.frame = frame;
        [self.myTabV setTableFooterView:FooterView];
    }
    return self;
}
-(void)confirmAction{
    if (self.delegate && [self.delegate respondsToSelector:@selector(confirmActionNumber:attr:)]) {
        NSMutableArray *array=[[NSMutableArray alloc]init];
        for (int i=0; i<self.specification.count; i++) {
            NSString *key=[NSString stringWithFormat:@"%d",i];
            [array addObject:self.selected[key]];
        }
        NSLog(@"%@",self.model.attr_val);
        if (![self.model.attr_val isEqualToString:@""]||(self.model.attr_val.length!=0)) {
            for (NSString *str in array) {
                if ([str isEqualToString:@""]||str.length==0) {
                    [PublicClass ProgressHUDModeText:@"请选择规格" andTime:2];
                    return;
                }
            }
        }
       
        NSLog(@"%@",[NSString stringWithFormat:@"%@",[array componentsJoinedByString:@"|"]]);
        [self.delegate confirmActionNumber:[NSString  stringWithFormat:@"%ld",(long)self.numberButton.currentNumber] attr:[NSString stringWithFormat:@"%@",[array componentsJoinedByString:@"|"]]];
    }
}
#pragma mark UITableView代理方法
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    
//}
////
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.specification.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float butX = 20;
    int Y = 0;
    
    SpecificationModel *model=self.specification[indexPath.row];
    for(int i = 0; i < model.val.count; i++){
        ValModel *valModel=model.val[i];
        //宽度自适应
        NSDictionary *fontDict = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
        CGRect frame = [valModel.name boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDict context:nil];
        float butW=frame.size.width;
        if (butW<10) {
            butW=10;
        }
        if (butX+butW+20>SCREEN_WIDTH-20) {
            butX = 20;
            Y++;
        }
        butX+= butW+30;
    }
    if (model.val.count==0) {
        return 0;
    }
    return (Y+1)*40+50.5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellid=@"CellID";
    SpecificationModel *model=self.specification[indexPath.row];
    
    SpecificationCell *cell = (SpecificationCell *)[tableView dequeueReusableCellWithIdentifier:cellid];
    if(cell==nil){
        cell = [[SpecificationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
    }
    cell.model=model;
    cell.delegate=self;
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
#pragma mark 懒加载
-(UITableView *)myTabV{
    if (!_myTabV) {
        _myTabV = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTabV.delegate=self;
        _myTabV.dataSource=self;
        _myTabV.backgroundColor=[UIColor colorWithRed:0.93f green:0.94f blue:0.94f alpha:1.00f];
        _myTabV.separatorStyle = UITableViewCellSelectionStyleNone;
        _myTabV.showsVerticalScrollIndicator=NO;
    }
    return _myTabV;
}
-(NSMutableArray *)specification{
    if (!_specification) {
        _specification=[[NSMutableArray alloc]init];
    }
    return  _specification;
}
-(NSMutableArray *)propertyArray{
    if (!_propertyArray) {
        _propertyArray=[[NSMutableArray alloc]init];
    }
    return  _propertyArray;
}
-(NSMutableArray *)classifyArray{
    if (!_classifyArray) {
        _classifyArray=[[NSMutableArray alloc]init];
    }
    return  _classifyArray;
}
-(NSMutableDictionary *)selected{
    if (!_selected) {
        _selected=[[NSMutableDictionary alloc]init];
        for (int i=0; i<self.specification.count; i++) {
            [_selected setObject:@"" forKey:[NSString stringWithFormat:@"%d",i]];
        }
    }
    return  _selected;
}

-(void)setModel:(DetailsModel *)model{
    _model=model;
    self.price.text=[NSString stringWithFormat:@"₱%@",model.goods_sale_price];
    self.repertory.text=[NSString stringWithFormat:@"%@:%@%@",Localized(@"库存"),model.goods_stock,Localized(@"件")];
    self.numberButton.maxValue = [model.goods_stock intValue];
    [self.goodsImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@union/%@",IMGURL,model.goods_file2]] placeholderImage:[UIImage imageNamed:@"图片空白页(小图)"]];
    
    [self.specification removeAllObjects];
    NSArray *array = [model.attr_val componentsSeparatedByString:@"||"]; //字符串按照||分隔成数组
    for (NSString *str in array) {
        NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
        NSArray *newArray = [str componentsSeparatedByString:@"|"];
        NSMutableArray *array=[NSMutableArray arrayWithArray:newArray];
        NSString *value=array[0];
        [array removeObjectAtIndex:0];
        
        NSMutableArray *valueArray=[[NSMutableArray alloc]init];
        for (NSString *str in array) {
            NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
            [dict setObject:[str subStringFrom:@"(" to:@")"] forKey:@"name"];
            [valueArray addObject:dict];
        }
        [dict setObject:value forKey:@"name"];
        [dict setObject:valueArray forKey:@"val"];
        
        SpecificationModel *model=[SpecificationModel yy_modelWithDictionary:dict];
        [self.specification addObject:model];
        [self.classifyArray addObject:value];
        self.classify.text = [NSString stringWithFormat:@"%@:%@",Localized(@"请选择"),[self.classifyArray componentsJoinedByString:@" "]];
    }
    [self.myTabV reloadData];
    [self propertyPrices:model];
}

-(void)propertyPrices:(DetailsModel *)model{
    NSLog(@"%@",model.attr_store);
    
    if (model.attr_store.length==0||model.attr_store==nil) {
        return;
    }
    
    NSArray *array = [model.attr_store componentsSeparatedByString:@"||"]; //字符串按照||分隔成数组
    for (NSString *str in array) {
        NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
        NSArray *newArray = [str componentsSeparatedByString:@"|"];
        NSString *price=newArray[newArray.count-2];
        NSString *inventory=newArray[newArray.count-1];

        NSMutableArray *array=[NSMutableArray arrayWithArray:newArray];
        [array removeLastObject];
        [array removeLastObject];

//        NSLog(@"%@---%@---%@",price,inventory,property);
        [dict setObject:price forKey:@"price"];
        [dict setObject:inventory forKey:@"inventory"];
        [dict setObject:array forKey:@"property"];
        
        PropertyModel *model=[PropertyModel yy_modelWithDictionary:dict];
        [self.propertyArray addObject:model];
    }
}

@end









